package com.fishing.util.personal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownLoadFile {
    /**
     * @Description:创建文件到本地
     * @param path:路径
     * @param data:数据
     * */
	public static void creatFile(String path,String data) throws UnsupportedEncodingException, IOException {
    	OutputStream fos = new FileOutputStream(path);
		fos.write(data.getBytes("UTF-8"));
		fos.close();
    }
    
	/**
	 * @Description:下载文件到客户端
	 * @param path:文件路径
	 * @throws IOException 
	 * @throws ServletException 
	 * */
    public static void doGet(HttpServletRequest request,HttpServletResponse response,String path) throws ServletException, IOException {
    	File file = new File(path);
    	if(!file.exists()) {
    		request.setAttribute("message","您要下载的资源已被删除");
    		request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
    	}
    	//处理文件名 
    	String filename  = path.substring(path.lastIndexOf('\\') + 1);
    	//设置响应头,控制浏览器文件下载该文件
    	response.setHeader("content-disposition", "attachment;filename=" + new String(filename.getBytes(),"ISO8859-1"));
    	//读取要下载 的文件，保存到文件输入流
    	FileInputStream in = new FileInputStream(path);
    	//创建输出流
    	OutputStream out = response.getOutputStream();
    	//创建缓冲区 
    	byte buffer[] = new byte[1];
    	int len = 0;
    	int Linefeed = 0;
    	/*String LINE = System.getProperty("line.separator");
    	if(LINE.equals(("\r"))) {
    		Linefeed = 10;
    	}else if(LINE.equals(("\n"))){
    		Linefeed = 13;
    	}else if(LINE.equals(("\r\n"))){
    		Linefeed = 1013;
    	}*/
    	String line = System.getProperty("line.separator");//换行
    	while((len = in.read()) != -1) {
    		if(len == 10 ) {
    			out.write(line.getBytes());
    			continue;
    		}
    		//输出缓冲区的内容到浏览器,实现下载
    		out.write(len);
    	}
    	in.close();
    	out.close();
    }
}
